package org.example.sqlsession;

import org.example.bean.User;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class MyExcutor implements Excutor {

    private MyConfiguration configuration = new MyConfiguration();

    @Override
    public <T> T query(String statement, Object parameter) {
        Connection connection = getConnection();
        ResultSet resultSet = null;
        PreparedStatement pre = null;
        try {
            pre = connection.prepareStatement(statement);
            pre.setLong(1, Long.parseLong((String) parameter));
            resultSet = pre.executeQuery();
            User user = new User();
            while (resultSet.next()) {
                user.setId(resultSet.getLong(1));
                user.setUserName(resultSet.getString(2));
                user.setPassword(resultSet.getString(3));
            }
            return (T) user;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (resultSet != null) {
                    resultSet.close();
                }
                if (pre != null) {
                    pre.close();
                }
                if (connection != null) {
                    connection.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
                ;
            }
        }
        return null;
    }

    private Connection getConnection() {
        Connection connection = configuration.build("config.xml");
        return connection;
    }
}
